﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using WebApplication1.Swagger;

namespace WebApplication1
{
    /// <summary>
    /// Swagger 扩展
    /// </summary>
    public static partial class Extensions
    {

        /// <summary>
        /// 配置自定义Swagger服务
        /// </summary>
        /// <param name="builder">应用程序生成器</param>
        public static IApplicationBuilder UseDefaultSwagger(this IApplicationBuilder builder)
        {
            builder.UseSwagger();
            builder.UseSwaggerUI(options =>
            {
                options.DocExpansion(DocExpansion.None);
                //options.SwaggerEndpoint("/swagger/v1/swagger.json", "api v1");
                SwaggerApi.ApiInfos.ForEach(x =>
                {
                    options.SwaggerEndpoint($"/swagger/{x.UrlPrefix}/swagger.json", x.Name);
                });
                // 模型的默认扩展深度，设置为 -1 完全隐藏模型
                options.DefaultModelsExpandDepth(-1);
                // API文档仅展开标记
                options.DocExpansion(DocExpansion.List);
                // API前缀设置为空
                options.RoutePrefix = string.Empty;
                options.DocumentTitle = "WebApi文档";
                //return;

            });
            return builder;
        }

        /// <summary>
        /// 初始化Swagger
        /// </summary>
        /// <param name="services"></param>
        public static void InitSwagger(this IServiceCollection services)
        {
            var assemblyName = Assembly.GetEntryAssembly().GetName().Name;
            //添加Swagger
            services.AddSwaggerGen(options =>
            {
                SwaggerApi.ApiInfos.ForEach(x =>
                {
                    options.SwaggerDoc(x.UrlPrefix, x.OpenApiInfo);
                });
                //解决相同类名会报错的问题
                options.CustomSchemaIds(type => type.FullName);
                //控制器注释
                options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{assemblyName}.xml"), true);
            });
        }

    }
}
